<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="filter-tags" v-if="hasActiveFilters">
      <span class="filter-label">已选条件：</span>
      <el-tag
        v-if="query.search"
        closable
        @close="clearFilter('search')"
        size="small"
        class="filter-tag"
      >
        关键词: {{ query.search }}
      </el-tag>
      <el-tag
        v-if="query.status"
        closable
        @close="clearFilter('status')"
        size="small"
        class="filter-tag"
        :type="getStatusType(query.status)"
      >
        状态: {{ formatStatus(query.status) }}
      </el-tag>
      <el-tag
        v-if="query.role"
        closable
        @close="clearFilter('role')"
        size="small"
        class="filter-tag"
      >
        角色: {{ query.role }}
      </el-tag>
      <el-tag
        v-if="query.startDate || query.endDate"
        closable
        @close="clearDateFilter()"
        size="small"
        class="filter-tag"
      >
        注册时间: {{ query.startDate || "-" }} 至 {{ query.endDate || "-" }}
      </el-tag>
      <el-button type="primary" link @click="resetFilters" size="small"
        >清空全部</el-button
      >
    </div>
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :changePage="changePage"
        :editFunc="handleEdit"
        :loading="loading"
      >
        <template #toolbarBtn>
          <el-button
            type="warning"
            :icon="CirclePlusFilled"
            @click="visible = true"
            >新增</el-button
          >
          <el-button type="primary" :icon="Download" @click="exportUsers"
            >导出</el-button
          >
        </template>
        <template #status="scope">
          <template v-if="scope.rows && scope.rows.status">
            <el-tag :type="getStatusType(scope.rows.status)">
              {{ formatStatus(scope.rows.status) }}
            </el-tag>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleChangeStatus(scope.rows)"
            >
              更改状态
            </el-button>
          </template>
          <template v-else>-</template>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
      />
    </el-dialog>
    <el-dialog
      title="查看详情"
      v-model="visible1"
      width="700px"
      destroy-on-close
    >
      <TableDetail :data="viewData" :loading="detailLoading"></TableDetail>
    </el-dialog>
    <el-dialog
      title="更改用户状态"
      v-model="statusDialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form ref="statusForm" :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(currentUser.status)">
            {{ formatStatus(currentUser.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择新状态">
            <el-option label="正常" value="normal"></el-option>
            <el-option label="禁言" value="muted"></el-option>
            <el-option label="封禁" value="banned"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原因" prop="reason">
          <el-input
            type="textarea"
            v-model="statusForm.reason"
            placeholder="请输入变更原因（可选）"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitStatusChange"
            :loading="statusLoading"
          >
            确认更改
          </el-button>
          <el-button @click="statusDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlusFilled, Download } from "@element-plus/icons-vue";
import { User, AdminUser } from "@/types/user";
import request from "@/utils/request";
import { FormOption, FormOptionList } from "@/types/form-option";

// 导入组件
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import TableEdit from "@/components/table-edit.vue";

export default {
  name: "system-user",
  components: {
    TableCustom,
    TableDetail,
    TableSearch,
    TableEdit,
    CirclePlusFilled,
    Download,
  },
  setup() {
    // 查询相关
    const query = reactive({
      search: "",
      status: "",
      role: "",
      startDate: "",
      endDate: "",
      sortBy: "createdAt",
      sortOrder: "desc",
    });

    const searchOpt = ref<FormOptionList[]>([
      {
        type: "input",
        label: "搜索：",
        prop: "search",
        placeholder: "用户名/邮箱/手机号",
      },
      {
        type: "select",
        label: "状态：",
        prop: "status",
        opts: [
          { label: "全部", value: "" },
          { label: "正常", value: "normal" },
          { label: "禁言", value: "muted" },
          { label: "封禁", value: "banned" },
        ],
      },
      {
        type: "select",
        label: "角色：",
        prop: "role",
        opts: [
          { label: "全部", value: "" },
          { label: "用户", value: "user" },
          { label: "管理员", value: "admin" },
        ],
      },
      {
        type: "datepicker",
        label: "注册时间：",
        prop: "date",
        format: "YYYY-MM-DD",
        placeholder: "选择日期范围",
        onChange: (val: [string, string]) => {
          if (val) {
            query.startDate = val[0];
            query.endDate = val[1];
          } else {
            query.startDate = "";
            query.endDate = "";
          }
        },
      },
    ]);

    const handleSearch = () => {
      changePage(1);
    };

    // 表格相关
    const loading = ref(false);
    const columns = ref([
      { type: "index", label: "序号", width: 55, align: "center" },
      { prop: "username", label: "用户名" },
      { prop: "email", label: "邮箱" },
      { prop: "phone", label: "手机号" },
      {
        prop: "status",
        label: "状态",
        slotName: "status",
      },
      { prop: "role", label: "角色" },
      {
        prop: "createdAt",
        label: "注册时间",
        formatter: (val: any) => {
          return new Date(val).toLocaleString();
        },
      },
      { prop: "operator", label: "操作", width: 250 },
    ]);

    // 状态格式化
    const formatStatus = (status: string) => {
      const statusMap: Record<string, string> = {
        normal: "正常",
        muted: "禁言",
        banned: "封禁",
      };
      return statusMap[status] || status;
    };

    // 获取状态对应的标签类型
    const getStatusType = (status: string) => {
      const typeMap: Record<string, string> = {
        normal: "success",
        muted: "warning",
        banned: "danger",
      };
      return typeMap[status] || "";
    };

    const page = reactive({
      index: 1,
      size: 10,
      total: 0,
    });

    const tableData = ref<AdminUser[]>([]);

    const getData = async () => {
      try {
        loading.value = true;
        const params = {
          page: page.index,
          limit: page.size,
          ...query,
        };

        const res = await request.get("/api/users/admin/users", params);
        if (res.success) {
          tableData.value = res.data.users;
          page.total = res.data.total;
        } else {
          ElMessage.error(res.message || "获取用户列表失败");
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
        ElMessage.error("获取用户列表失败");
      } finally {
        loading.value = false;
      }
    };

    const changePage = (val: number) => {
      page.index = val;
      getData();
    };

    // 导出用户
    const exportUsers = () => {
      ElMessageBox.confirm("确定要导出当前筛选条件下的用户数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          ElMessage.success("导出成功");
          // 这里可以添加实际的导出逻辑
        })
        .catch(() => {});
    };

    // 新增/编辑弹窗相关
    const options = ref<FormOption>({
      labelWidth: "100px",
      span: 12,
      list: [
        { type: "input", label: "用户名", prop: "username", required: true },
        { type: "input", label: "手机号", prop: "phone", required: true },
        { type: "input", label: "密码", prop: "password", required: true },
        { type: "input", label: "邮箱", prop: "email", required: true },
        {
          type: "select",
          label: "角色",
          prop: "role",
          required: true,
          opts: [
            { label: "用户", value: "user" },
            { label: "管理员", value: "admin" },
          ],
        },
        {
          type: "select",
          label: "状态",
          prop: "status",
          required: true,
          opts: [
            { label: "正常", value: "normal" },
            { label: "禁言", value: "muted" },
            { label: "封禁", value: "banned" },
          ],
        },
      ],
    });

    const visible = ref(false);
    const isEdit = ref(false);
    const rowData = ref({});

    const handleEdit = (row: AdminUser) => {
      rowData.value = { ...row };
      isEdit.value = true;
      visible.value = true;
    };

    const updateData = async (formData: any) => {
      try {
        if (isEdit.value) {
          // 编辑用户
          const res = await request.put(
            `/api/users/admin/users/${formData._id}`,
            formData
          );
          if (res.success) {
            ElMessage.success("编辑成功");
            closeDialog();
            getData();
          } else {
            ElMessage.error(res.message || "编辑失败");
          }
        } else {
          // 新增用户
          const res = await request.post("/api/users/admin/register", formData);
          if (res.success) {
            ElMessage.success("新增成功");
            closeDialog();
            getData();
          } else {
            ElMessage.error(res.message || "新增失败");
          }
        }
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    };

    const closeDialog = () => {
      visible.value = false;
      isEdit.value = false;
      rowData.value = {};
    };

    // 查看详情弹窗相关
    const visible1 = ref(false);
    const detailLoading = ref(false);
    const viewData = ref({
      row: {},
      list: [],
    });

    const handleView = async (row: AdminUser) => {
      try {
        detailLoading.value = true;
        visible1.value = true;

        // 获取用户详情
        const res = await request.get(`/api/users/admin/users/${row._id}`);

        if (res.success) {
          // 修正：用户数据在res.data.user中，而不是直接在res.data中
          const userDetail = res.data.user || res.data;
          viewData.value.row = { ...userDetail };
          viewData.value.list = [
            { prop: "_id", label: "用户ID" },
            { prop: "username", label: "用户名" },
            { prop: "email", label: "邮箱" },
            { prop: "phone", label: "手机号" },
            { prop: "role", label: "角色" },
            { prop: "status", label: "状态" },
            {
              prop: "createdAt",
              label: "注册时间",
              formatter: (val: string) => new Date(val).toLocaleString(),
            },
            {
              prop: "lastLoginAt",
              label: "最后登录时间",
              formatter: (val: string) =>
                val ? new Date(val).toLocaleString() : "未登录",
            },
            { prop: "statusReason", label: "状态原因" },
            { prop: "studentId", label: "学号/工号" },
          ];
        } else {
          ElMessage.error(res.message || "获取用户详情失败");
          visible1.value = false;
        }
      } catch (error) {
        console.error("获取用户详情失败:", error);
        ElMessage.error("获取用户详情失败");
        visible1.value = false;
      } finally {
        detailLoading.value = false;
      }
    };

    // 删除相关
    const handleDelete = (row: AdminUser) => {
      ElMessageBox.confirm(`确定要删除用户"${row.username}"吗?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await request.delete(
              `/api/users/admin/users/${row._id}`
            );
            if (res.success) {
              ElMessage.success("删除成功");
              getData();
            } else {
              ElMessage.error(res.message || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            ElMessage.error("删除失败");
          }
        })
        .catch(() => {});
    };

    // 更改用户状态相关
    const statusDialogVisible = ref(false);
    const statusLoading = ref(false);
    const currentUser = ref<any>({});
    const statusForm = reactive({
      status: "",
      reason: "",
    });

    const handleChangeStatus = (row: AdminUser) => {
      currentUser.value = { ...row };
      statusForm.status = row.status;
      statusForm.reason = "";
      statusDialogVisible.value = true;
    };

    const submitStatusChange = async () => {
      if (!statusForm.status) {
        ElMessage.warning("请选择新状态");
        return;
      }

      try {
        statusLoading.value = true;
        const res = await request.put(
          `/api/users/admin/users/${currentUser.value._id}/status`,
          statusForm
        );
        if (res.success) {
          ElMessage.success("状态更新成功");
          statusDialogVisible.value = false;
          getData(); // 刷新数据
        } else {
          ElMessage.error(res.message || "状态更新失败");
        }
      } catch (error) {
        console.error("状态更新失败:", error);
        ElMessage.error("状态更新失败");
      } finally {
        statusLoading.value = false;
      }
    };

    const hasActiveFilters = computed(() => {
      return (
        query.search ||
        query.status ||
        query.role ||
        query.startDate ||
        query.endDate
      );
    });

    const clearFilter = (prop: string) => {
      query[prop] = "";
      changePage(1);
    };

    const clearDateFilter = () => {
      query.startDate = "";
      query.endDate = "";
      changePage(1);
    };

    const resetFilters = () => {
      Object.keys(query).forEach((prop) => {
        query[prop] = "";
      });
      changePage(1);
    };

    onMounted(() => {
      getData();
    });

    return {
      query,
      searchOpt,
      handleSearch,
      loading,
      columns,
      page,
      tableData,
      getData,
      changePage,
      exportUsers,
      options,
      visible,
      isEdit,
      rowData,
      handleEdit,
      updateData,
      closeDialog,
      visible1,
      detailLoading,
      viewData,
      handleView,
      handleDelete,
      CirclePlusFilled,
      Download,
      formatStatus,
      getStatusType,
      statusDialogVisible,
      statusLoading,
      currentUser,
      statusForm,
      handleChangeStatus,
      submitStatusChange,
      hasActiveFilters,
      clearFilter,
      clearDateFilter,
      resetFilters,
    };
  },
};
</script>

<style scoped>
.container {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-tags {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-label {
  margin-right: 10px;
  font-weight: bold;
}

.filter-tag {
  margin-right: 10px;
}
</style>
